package flc.ast.fragment;

import android.app.Dialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.TouchUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.ProtectionRecordActivity;
import flc.ast.bean.MyProtectionBean;
import flc.ast.databinding.FragmentProtectionBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.OnSwipeTouchListener;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.TimeUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProtectionFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProtectionFragment extends BaseNoModelFragment<FragmentProtectionBinding> {

    private List<String> listShow = new ArrayList<>();
    private boolean isOpen;
    private Dialog myAddDialog;
    private EditText dialogText;
    private Handler mHandler;
    private int mRecordTime;
    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mHandler.postDelayed(this, 1000);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.fragment_protection;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivProtectionRecord.setOnClickListener(this);
        mDataBinding.llCustom.setOnClickListener(this);

        mHandler = new Handler();

        mDataBinding.ivOpen.setOnTouchListener(new View.OnTouchListener() {

            private float mPosX = 0, mPosY = 0, mCurPosX = 0, mCurPosY = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        mPosX = event.getX();
                        mPosY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mCurPosX = event.getX();
                        mCurPosY = event.getY();
                        if (mCurPosY - mPosY > 0 && Math.abs(mCurPosY - mPosY) > 5) {
                            //向下滑動
                            if (isOpen) {
                                isOpen = false;
                                mDataBinding.ivOpen.setImageResource(R.drawable.dakk);
                                stopRecordTime();
                                saveRecord();
                                getData();
                            }
                        } else if (mCurPosY - mPosY < 0 && Math.abs(mCurPosY - mPosY) > 5) {
                            //向上滑动
                            if (!isOpen) {
                                if (listShow == null || listShow.size() == 0) {
                                    ToastUtils.showShort(getString(R.string.please_custom_dns));
                                } else {
                                    isOpen = true;
                                    mDataBinding.ivOpen.setImageResource(R.drawable.gb);
                                    startRecordTime();
                                }
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return true;
            }
        });

        //添加弹框
        addDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivProtectionRecord://保护记录
                startActivity(ProtectionRecordActivity.class);
                break;
            case R.id.llCustom://自定义拦截保护域名
                myAddDialog.show();
                break;
            //添加弹框
            case R.id.tvDialogAddCancel://取消
                myAddDialog.dismiss();
                break;
            case R.id.tvDialogAddConfirm://确定
                String name = dialogText.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getString(R.string.please_input_dns));
                    return;
                }
                List<String> listSave = new ArrayList<>();
                listSave.add(name);
                List<String> listSp = AppSpUtils.getProtectionList();
                if (listSp != null && listSp.size() > 0) {
                    listSp.addAll(0, listSave);
                    AppSpUtils.saveProtectionList(listSp);
                } else {
                    AppSpUtils.saveProtectionList(listSave);
                }
                myAddDialog.dismiss();
                getData();
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        if (listShow != null) {
            listShow.clear();
        }
        listShow = AppSpUtils.getProtectionList();
        int num = 0;
        List<MyProtectionBean> listSp = AppSpUtils.getProtectionRecordList();
        if (listSp != null && listSp.size() != 0) {
            String today = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
            for (MyProtectionBean myProtectionBean : listSp) {
                String date = TimeUtils.millis2String(myProtectionBean.getTime(), new SimpleDateFormat("yyyy-MM-dd"));
                if (today.equals(date)) {
                    num++;
                }
            }
            mDataBinding.tvTodayFrequency.setText(num + getString(R.string.unit_frequency));
            mDataBinding.tvFrequency.setText(listSp.size() + getString(R.string.unit_frequency));
        } else {
            mDataBinding.tvTodayFrequency.setText(0 + getString(R.string.unit_frequency));
            mDataBinding.tvFrequency.setText(0 + getString(R.string.unit_frequency));
        }
    }

    private void saveRecord() {
        if (mRecordTime < 1) return;
        List<MyProtectionBean> listSave = new ArrayList<>();
        for (String s : listShow) {
            listSave.add(new MyProtectionBean(s, TimeUtil.getHHmmss(mRecordTime * 1000L), TimeUtils.getNowMills()));
        }
        List<MyProtectionBean> listSp = AppSpUtils.getProtectionRecordList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(0, listSave);
            AppSpUtils.saveProtectionRecordList(listSp);
        } else {
            AppSpUtils.saveProtectionRecordList(listSave);
        }
    }

    //添加弹框
    private void addDialog() {
        myAddDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add, null);
        myAddDialog.setContentView(inflate);
        myAddDialog.setCancelable(true);
        Window dialogWindow = myAddDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddCancel);
        dialogText = inflate.findViewById(R.id.etDialogAddName);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //开始
    private void startRecordTime() {
        mRecordTime = 0;
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

}